package com.gs.djys.checkfragments.inquest;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.TimePickerView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.gs.djys.Base.AddBean;
import com.gs.djys.Base.DictationResult;
import com.gs.djys.Base.MyAppliCation;
import com.gs.djys.R;
import com.gs.djys.Util.MinePopupWindow;
import com.gs.djys.Util.NoRecycleView;
import com.gs.djys.Util.ToastUtils;
import com.gs.djys.Util.Utils;
import com.gs.djys.adapter.LGRecycleViewAdapter;
import com.gs.djys.adapter.LGViewHolder;
import com.gs.djys.mvp.MVPBaseFragment;
import com.gs.djys.signtext.SignTextActivity;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.lxj.matisse.CaptureMode;
import com.lxj.matisse.Matisse;
import com.lxj.matisse.MimeType;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public class InquestFragment extends MVPBaseFragment<InquestContract.View, InquestPresenter> implements InquestContract.View, RadioGroup.OnCheckedChangeListener {


    @Bind(R.id.rb_Male)
    RadioButton rbMale;
    @Bind(R.id.rb_FeMale)
    RadioButton rbFeMale;
    @Bind(R.id.rg_sex)
    RadioGroup rgSex;
    @Bind(R.id.sljg_lay)
    LinearLayout sljgLay;
    @Bind(R.id.jcsj_et)
    TextView jcsjEt;
    @Bind(R.id.jcsj_lay)
    LinearLayout jcsjLay;
    @Bind(R.id.jcdd_et)
    EditText jcddEt;
    @Bind(R.id.cphm_te)
    TextView cphmTe;
    @Bind(R.id.zhfb_te)
    TextView zhfbTe;
    @Bind(R.id.hwmc_te)
    TextView hwmcTe;
    @Bind(R.id.hwcc_c)
    EditText hwccC;
    @Bind(R.id.hwcc_k)
    EditText hwccK;
    @Bind(R.id.hwcc_g)
    EditText hwccG;
    @Bind(R.id.chzz_c)
    EditText chzzC;
    @Bind(R.id.chzz_k)
    EditText chzzK;
    @Bind(R.id.chzz_g)
    EditText chzzG;
    @Bind(R.id.chzz_et)
    EditText chzzEt;
    @Bind(R.id.yslx_te)
    TextView yslxTe;
    @Bind(R.id.fj_te)
    TextView fjTe;
    @Bind(R.id.bz_et)
    EditText bzEt;
    @Bind(R.id.INQuality)
    RelativeLayout INQuality;
    @Bind(R.id.bz_lay)
    RelativeLayout bzLay;
    @Bind(R.id.gd_te)
    TextView gdTe;
    @Bind(R.id.pic)
    ImageView pic;
    @Bind(R.id.chzqz_te)
    TextView chzqzTe;
    @Bind(R.id.chz_lay)
    LinearLayout chzLay;
    @Bind(R.id.lxdh_et)
    EditText lxdhEt;
    @Bind(R.id.cxcljcd_img)
    ImageView cxcljcdImg;
    @Bind(R.id.jcd_lay)
    RelativeLayout jcdLay;
    @Bind(R.id.recycleview)
    NoRecycleView recycleview;
    @Bind(R.id.jcr2_te)
    TextView jcr2Te;
    @Bind(R.id.jczfzr_te)
    TextView jczfzrTe;
    @Bind(R.id.jczfzr_lay)
    LinearLayout jczfzrLay;
    @Bind(R.id.fzkfzr_te)
    TextView fzkfzrTe;
    @Bind(R.id.fzkfzr_lay)
    LinearLayout fzkfzrLay;
    @Bind(R.id.zfc_te)
    TextView zfcTe;
    @Bind(R.id.zfcfgfzr_lay)
    LinearLayout zfcfgfzrLay;
    @Bind(R.id.time)
    TextView time;
    @Bind(R.id.ty_lay)
    LinearLayout tyLay;
    @Bind(R.id.zkms_et)
    EditText zkmsEt;
    @Bind(R.id.INQuality2)
    RelativeLayout INQuality2;
    @Bind(R.id.bty_lay)
    LinearLayout btyLay;
    @Bind(R.id.add_te)
    TextView addTe;
    @Bind(R.id.relativeLayout)
    RelativeLayout relativeLayout;
    private String isty = "1";
    private int CHOOSE_PICTURE_CODE = 66;
    private int REQUEST_CODE_CHOOSE = 88;//相册相机
    private String TPTYPE = "";
    private String DRIVER_SIGN = "";
    private MinePopupWindow minePopupWindow;
    private SimpleDateFormat simpleDateFormat;
    private List<String> PicDatas = new ArrayList<>();
    private String CHECK_IMG;
    private static String APPID = "5bf211f5";
    private String dictationResultStr;
    private List<String> xf = new ArrayList<>();
    private List<String> zong = new ArrayList<>();

    @Override
    public void onRequestError(String msg) {
        ToastUtils.showShortToast(msg);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fra_inquest, container, false);
        ButterKnife.bind(this, view);
        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        jcsjEt.setText(simpleDateFormat.format(calendar.getTime()));
        time.setText(simpleDateFormat.format(calendar.getTime()));
        rgSex.setOnCheckedChangeListener(this);
        mPresenter.getData(MyAppliCation.spUtils.getString("REQ_NO"));
        return view;
    }

    private void setAdapter() {
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recycleview.setLayoutManager(manager);
        LGRecycleViewAdapter<String> adapter = new LGRecycleViewAdapter<String>(PicDatas) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_sign_fag;
            }

            @Override
            public void convert(LGViewHolder holder, String zCDBean, int position) {
                ImageView PicView = (ImageView) holder.getView(R.id.img_view);
                if (!Utils.isDestroy(getActivity())) {
                    Glide.with(getActivity())
                            .load("data:image/png;base64," + PicDatas.get(position))
                            .into(PicView);
                }
            }
        };
        recycleview.setAdapter(adapter);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.time, R.id.jcsj_lay, R.id.cxcljcd_img, R.id.chzqz_te, R.id.jcr2_te, R.id.add_te, R.id.INQuality, R.id.INQuality2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.INQuality:
                getkdxf(bzEt);
                break;
            case R.id.INQuality2:
                getkdxf(zkmsEt);
                break;
            case R.id.time:
                TimePickerView pvTime2 = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        time.setText(simpleDateFormat.format(date));
                    }
                }).setType(new boolean[]{true, true, true, false, false, false})
                        .build();
                pvTime2.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime2.show();
                break;
            case R.id.jcsj_lay:
                TimePickerView pvTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        jcsjEt.setText(simpleDateFormat.format(date));
                    }
                }).setType(new boolean[]{true, true, true, false, false, false})
                        .build();
                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
                break;
            case R.id.cxcljcd_img:
                if (minePopupWindow == null) {
                    minePopupWindow = new MinePopupWindow(getActivity(), itemOnClick);
                }
                minePopupWindow.showAtLocation(relativeLayout, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.chzqz_te:
                TPTYPE = "车货主";
                Intent intent = new Intent(getActivity(), SignTextActivity.class);
                startActivityForResult(intent, CHOOSE_PICTURE_CODE);
                break;
            case R.id.jcr2_te:
                TPTYPE = "检测人";
                Intent intent3 = new Intent(getActivity(), SignTextActivity.class);
                startActivityForResult(intent3, CHOOSE_PICTURE_CODE);
                break;
            case R.id.add_te:
                if (isty.equals("1")) {
                    if (PicDatas.size() > 0) {
                        String SIGN1 = "";
                        for (int i = 0; i < PicDatas.size(); i++) {
                            if (PicDatas.size() == 1) {
                                SIGN1 = PicDatas.get(i);
                            } else {
                                SIGN1 += PicDatas.get(i) + ",";
                            }
                        }
                        AddInquestBean addInquestBean = new AddInquestBean();
                        addInquestBean.setReq_no(MyAppliCation.spUtils.getString("REQ_NO"));
                        addInquestBean.setCARGO_LENGTH(hwccC.getText().toString());//货物长
                        addInquestBean.setCARGO_WIDTH(hwccK.getText().toString());//货物宽
                        addInquestBean.setCARGO_HEIGHT(hwccG.getText().toString());//货物高
                        addInquestBean.setTOTAL_LENGTH(chzzC.getText().toString());//货物长
                        addInquestBean.setTOTAL_WIDTH(chzzK.getText().toString());//货物宽
                        addInquestBean.setTOTAL_HEIGHT(chzzG.getText().toString());//货物高
                        addInquestBean.setTOTAL_WEIGHT(chzzEt.getText().toString());//车辆总重
                        addInquestBean.setROADS(yslxTe.getText().toString());//运输路线
                        addInquestBean.setCHECK_TIME(jcsjEt.getText().toString());//检测时间
                        addInquestBean.setCHECK_DIST(jcddEt.getText().toString());//检测地点
                        addInquestBean.setDRIVER_PHONE(lxdhEt.getText().toString());//联系电话
                        addInquestBean.setCOMMENT(bzEt.getText().toString());//备注
                        addInquestBean.setDRIVER_SIGN(DRIVER_SIGN);//车货主签字
                        addInquestBean.setCHECK_IMG(CHECK_IMG);//超限车辆检测单
                        addInquestBean.setSIGN1(SIGN1);//检测人签字
                        addInquestBean.setSIGN2("");//检测站负责人签字
                        addInquestBean.setSIGN3("");//法制科负责人签字
                        addInquestBean.setSIGN4("");//执法处分管副处长签字
                        addInquestBean.setCREAETE_TIME(time.getText().toString());//签字时间
                        String json = new Gson().toJson(addInquestBean);
                        mPresenter.addData("true", json, getActivity());
                    } else {
                        ToastUtils.showShortToast("检测人签字不能为空");
                    }
                } else {
                    AddInquestBean addInquestBean = new AddInquestBean();
                    addInquestBean.setReq_no(MyAppliCation.spUtils.getString("REQ_NO"));
                    addInquestBean.setCOMMENT(zkmsEt.getText().toString());
                    String json = new Gson().toJson(addInquestBean);
                    mPresenter.addData("false", json, getActivity());
                }
                break;
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup arg0, int checkId) {
        // TODO Auto-generated method stub
        switch (checkId) {
            case R.id.rb_Male:
                tyLay.setVisibility(View.VISIBLE);
                btyLay.setVisibility(View.GONE);
                isty = "1";
                break;
            case R.id.rb_FeMale:
                tyLay.setVisibility(View.GONE);
                btyLay.setVisibility(View.VISIBLE);
                isty = "0";
                break;
            default:
                break;
        }
    }

    @Override
    public void getDatas(InquestBean inquestBean) {
        if (inquestBean != null && inquestBean.getData() != null) {
            cphmTe.setText(inquestBean.getData().getVEHICLE_NO() + "," + inquestBean.getData().getVEHICLE_NO1());
            zhfbTe.setText(inquestBean.getData().getAXLES_LOAD());
            hwmcTe.setText(inquestBean.getData().getCARGO_INFO());
            hwccC.setText(inquestBean.getData().getCARGO_LENGTH());
            hwccK.setText(inquestBean.getData().getCARGO_WIDTH());
            hwccG.setText(inquestBean.getData().getCARGO_HEIGHT());
            chzzC.setText(inquestBean.getData().getTOTAL_LENGTH());
            chzzK.setText(inquestBean.getData().getTOTAL_WIDTH());
            chzzG.setText(inquestBean.getData().getTOTAL_HEIGHT());
            chzzEt.setText(inquestBean.getData().getTOTAL_WEIGHT());
            yslxTe.setText(inquestBean.getData().getROADS());
        }
    }

    @Override
    public void addDatas(AddBean addBean) {
        ToastUtils.showShortToast("提交成功");
        Intent intent = new Intent();
        getActivity().setResult(2, intent);
        getActivity().finish();
    }

    /**
     * 自定义pop监听
     */
    private View.OnClickListener itemOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.mine_camera_btn:
                    if (minePopupWindow.isShowing()) {
                        minePopupWindow.dismiss();
                    }
                    getFromCamera();
                    break;
                case R.id.mine_photo_btn:
                    if (minePopupWindow.isShowing()) {
                        minePopupWindow.dismiss();
                    }
                    getFromPhoto();
                    break;
                case R.id.mine_cancel_btn:
                    if (minePopupWindow.isShowing()) {
                        minePopupWindow.dismiss();
                    }
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 从相册获取
     */
    public void getFromPhoto() {
        Matisse.from(this)
                .choose(MimeType.ofImage()) //显示所有文件类型，比如图片和视频，
                .maxSelectable(1)
                .isCrop(true) //开启裁剪
                .forResult(REQUEST_CODE_CHOOSE); //请求码
    }

    /**
     * 照相获取
     */
    public void getFromCamera() {
        Matisse.from(this)
                .jumpCapture(CaptureMode.Image)//只拍照片
                .isCrop(true) //开启裁剪
                .forResult(REQUEST_CODE_CHOOSE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 88 && resultCode == RESULT_OK) {
            String cropPath = Matisse.obtainCropResult(data);
            if (!Utils.isDestroy(getActivity())) {
                Glide.with(getActivity())
                        .load(cropPath)
                        .into(cxcljcdImg);
            }
            CHECK_IMG = Utils.bmpToBase64String(cropPath);
        } else if (requestCode == CHOOSE_PICTURE_CODE && resultCode == -2) {
            if (TPTYPE.equals("车货主")) {
                pic.setVisibility(View.VISIBLE);
                chzqzTe.setVisibility(View.GONE);
                DRIVER_SIGN = data.getStringExtra("strBlob");
                if (!Utils.isDestroy(getActivity())) {
                    Glide.with(getActivity())
                            .load("data:image/png;base64," + DRIVER_SIGN)
                            .into(pic);
                }
            }
            if (TPTYPE.equals("检测人")) {
                PicDatas.add(data.getStringExtra("strBlob"));
                setAdapter();
            }
        }
    }

    private void getkdxf(final EditText kdaxfdate) {
        dictationResultStr = "[";
        // 语音配置对象初始化
        SpeechUtility.createUtility(getActivity(), SpeechConstant.APPID + "=" + APPID);
        // 1.创建SpeechRecognizer对象，第2个参数：本地听写时传InitListener
        SpeechRecognizer mIat = SpeechRecognizer.createRecognizer(getActivity(), null);
        // 交互动画
        final RecognizerDialog iatDialog = new RecognizerDialog(getActivity(), null);
        // 2.设置听写参数，详见《科大讯飞MSC API手册(Android)》SpeechConstant类
        mIat.setParameter(SpeechConstant.DOMAIN, "iat");
        mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        mIat.setParameter(SpeechConstant.ACCENT, "mandarin");
        // 3.开始听写
        iatDialog.setListener(new RecognizerDialogListener() {
            @Override
            public void onResult(RecognizerResult results, boolean isLast) {

                if (!isLast) {
                    dictationResultStr += results.getResultString() + ",";
                } else {
                    dictationResultStr += results.getResultString() + "]";
                }
                if (isLast) {
                    List<DictationResult> dictationResultList = JSON.parseArray(dictationResultStr, DictationResult.class);
                    String finalResult = "";
                    for (int i = 0; i < dictationResultList.size() - 1; i++) {
                        finalResult += dictationResultList.get(i)
                                .toString();
                    }
                    xf.clear();
                    zong.clear();
                    zong.add(kdaxfdate.getText().toString());
                    zong.add(finalResult);
                    kdaxfdate.setText(listToString2(zong));
                    kdaxfdate.requestFocus();
                    kdaxfdate.setSelection(listToString2(zong).length());
                }
            }

            @Override
            public void onError(SpeechError error) {
                error.getPlainDescription(true);
            }

        });
        iatDialog.show();

    }

    public static String listToString2(List<String> list) {
        StringBuilder sb = new StringBuilder();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (i < list.size() - 1) {
                    sb.append(list.get(i));
                } else {
                    sb.append(list.get(i));
                }
            }
        }
        return sb.toString();
    }
}